package sq

type Mapper struct {
	db *DB
	SqlBuilder
}

// Table 选择表名
func Table(tableName string) *Mapper {
	db := &DB{database: GetDB(defaultLink)}
	return &Mapper{db: db, SqlBuilder: SqlBuilder{table: tableName, dialect: newDialect(db.DriverName())}}
}

// ShowSQL 显示SQL语句
func (m *Mapper) ShowSQL() *Mapper {
	m.db.logging = true
	return m
}

//Insert 插入一条记录。
func (m *Mapper) Insert(data map[string]interface{}) (lastInsertId int64, err error) {
	result, err := m.db.Exec(m.insertString(data), m.args...)
	if err != nil {
		return 0, err
	}
	return result.LastInsertId()
}

//Delete 物理删除一条记录。
func (m *Mapper) Delete() (affected int64, err error) {
	result, err := m.db.Exec(m.deleteString(), m.args...)
	if err != nil {
		return 0, err
	}

	return result.RowsAffected()
}

//Update 更新一条记录。
func (m *Mapper) Update(data map[string]interface{}) (affected int64, err error) {
	result, err := m.db.Exec(m.updateString(data), m.args...)
	if err != nil {
		return 0, err
	}

	return result.RowsAffected()
}

//Where
func (m *Mapper) Where(str string, args ...interface{}) *Mapper {
	m.SqlBuilder.Where(str, args...)
	return m
}

//Count
func (m *Mapper) Count() (num int64, err error) {
	err = m.db.Take(&num, m.countString(), m.args...)
	return num, err
}
